package com.dex4d.ui.main.adapter;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.dex4d.R;
import com.dex4d.constants.AppConstants;
import com.dex4d.glide.GlideUtil;
import com.dex4d.ui.main.activity.AccountActivity;
import com.dex4d.ui.main.model.AccountCoin;
import com.dex4d.ui.main.model.HomeModel;
import com.dex4d.ui.main.model.TokenDetail;
import com.dex4d.utils.BalanceUtils;
import com.dex4d.utils.MoneyUtils;
import com.dex4d.utils.SPUtil;
import com.framework.bigdecimalutils.DoubleFormatTool;
import com.framework.util.DisplayUtil;
import com.yqritc.recyclerviewflexibledivider.FlexibleDividerDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 作者    LiQingyi
 * 时间    2018/10/31 13:56
 * 文件    dex4d-android
 * 描述
 */
public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements FlexibleDividerDecoration.VisibilityProvider {

    private static final int HEAD_TYPE = 0;
    private static final int TITLE_TYPE = 1;
    private static final int TOKEN_TYPE = 2;

    private List<HomeModel> list;
    private Activity context;
    private LayoutInflater inflater;
    private RecyclerView recyclerView;

    public HomeAdapter(Activity context, RecyclerView recyclerView) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.recyclerView = recyclerView;
        list = new ArrayList<>();
        list.add(new HomeModel(HEAD_TYPE));
        list.add(new HomeModel(TITLE_TYPE));

    }

    /**
     * 更新头部数据
     *
     * @param coin
     */
    public void updateTopData(AccountCoin coin) {
        HomeModel homeModel = list.get(0);
        homeModel.totalTokenBalance = coin.coins.total;
        homeModel.totalDex4DBalance = coin.d4d.total;
        homeModel.totalCapital = DoubleFormatTool.add2(coin.coins.total, coin.d4d.totalPrice, coin.dividends.total,2);
        notifyDataSetChanged();
    }

    /**
     * 更新数据
     *
     * @param tokenList
     */
    public void updateTokenData(final List<TokenDetail> tokenList) {
        if (tokenList == null || tokenList.isEmpty())
            return;

        Collections.sort(tokenList, new TokenDetail());


        if (list.size() > 2) {//说明已添加数据，只需要更新数据即可
            for (int i = 0; i < tokenList.size(); i++) {
                list.get(i + 2).token = tokenList.get(i);
            }
        } else {//增加新数据
            for (int i = 0; i < tokenList.size(); i++) {
                list.add(new HomeModel(TOKEN_TYPE, tokenList.get(i)));
            }
        }

        HomeModel topModel = list.get(0);
        topModel.tokenDetailList = tokenList;

        recyclerView.post(() -> {
            //TODO 局部刷新操作
            notifyItemRangeChanged(2, tokenList.size(), tokenList);
        });
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
        int type = getItemViewType(position);
        if (type == HEAD_TYPE) {
            View view = inflater.inflate(R.layout.home_item_rv_head, viewGroup, false);
            return new HeaderHolder(view);
        } else if (type == TITLE_TYPE) {
            View view = inflater.inflate(R.layout.home_item_rv_token_title, viewGroup, false);
            return new TitleHolder(view);
        } else {
            View view = inflater.inflate(R.layout.home_item_rv_token, viewGroup, false);
            return new TokenHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        int type = getItemViewType(position);
        if (type == HEAD_TYPE) {//头部信息

            final HomeModel model = list.get(position);
            viewHolder.itemView.setOnClickListener(v -> AccountActivity.start(context, model));
            HeaderHolder vh = (HeaderHolder) viewHolder;
            vh.txt_my_balance.setText(BalanceUtils.format(model.totalTokenBalance));
            vh.txt_4d_total.setText(BalanceUtils.format(model.totalDex4DBalance));
            vh.txt_head_total.setText(MoneyUtils.getSymbol());

            String xing = context.getResources().getString(R.string.xing);

            if (SPUtil.getBoolean(AppConstants.SP_HOME_EYE_KEY)){
                vh.img_eye.setImageResource(R.drawable.home_ic_open);
                vh.txt_head_value.setText(MoneyUtils.showMoney(model.totalCapital));
                vh.txt_head_value.setPadding(0,DisplayUtil.dip2px(context,4),0,0);
            }else {
                vh.img_eye.setImageResource(R.drawable.home_ic_close);
                vh.txt_head_value.setText(xing);
                vh.txt_head_value.setPadding(0,DisplayUtil.dip2px(context,18),0,0);
            }

            vh.img_eye.setOnClickListener(v -> {
                if (SPUtil.getBoolean(AppConstants.SP_HOME_EYE_KEY)){
                    vh.img_eye.setImageResource(R.drawable.home_ic_close);
                    SPUtil.putBoolean(AppConstants.SP_HOME_EYE_KEY,false);
                    vh.txt_head_value.setText(xing);
                    vh.txt_head_value.setPadding(0,DisplayUtil.dip2px(context,18),0,0);
                }else {
                    vh.img_eye.setImageResource(R.drawable.home_ic_open);
                    SPUtil.putBoolean(AppConstants.SP_HOME_EYE_KEY,true);
                    vh.txt_head_value.setText(MoneyUtils.showMoney(model.totalCapital));
                    vh.txt_head_value.setPadding(0,DisplayUtil.dip2px(context,4),0,0);
                }
            });

            vh.txt_home_pending.setText(getPending(5));

        } else if (type == TITLE_TYPE) {

        } else {//币列表
            TokenDetail tokenDetail = list.get(position).token;
            TokenHolder tokenHolder = (TokenHolder) viewHolder;
            updateItem(tokenDetail, tokenHolder);
        }
    }

    public void updateItem(TokenDetail tokenDetail, TokenHolder tokenHolder) {
        GlideUtil.displayImg(tokenHolder.img_coin, tokenDetail.logo);
        tokenHolder.txt_coin_name.setText(tokenDetail.symbol.toUpperCase());
        tokenHolder.txt_coin_price.setText(tokenDetail.whitout_fee_price);


        if (DoubleFormatTool.compare(tokenDetail.whitout_fee_price, tokenDetail.pre_24hours_price) > 0) {//涨
            tokenHolder.txt_coin_change.setText("+"+DoubleFormatTool.percent(tokenDetail.whitout_fee_price, tokenDetail.pre_24hours_price, 6));
            int color = context.getResources().getColor(R.color.account_token_up);
            tokenHolder.txt_coin_price.setTextColor(color);
            tokenHolder.txt_coin_change.setTextColor(color);
        }

        else if (DoubleFormatTool.compare(tokenDetail.whitout_fee_price, tokenDetail.pre_24hours_price) == 0) {
            tokenHolder.txt_coin_change.setText(DoubleFormatTool.percent(tokenDetail.whitout_fee_price, tokenDetail.pre_24hours_price, 6));
            int color = context.getResources().getColor(R.color.white);
            tokenHolder.txt_coin_price.setTextColor(color);
            tokenHolder.txt_coin_change.setTextColor(color);
        }

        else {//跌
            tokenHolder.txt_coin_change.setText("-"+DoubleFormatTool.percent(tokenDetail.whitout_fee_price, tokenDetail.pre_24hours_price, 6));
            int color = context.getResources().getColor(R.color.account_token_down);
            tokenHolder.txt_coin_price.setTextColor(color);
            tokenHolder.txt_coin_change.setTextColor(color);
        }

        //更新 状态 字段显示
        updateShowState(tokenHolder.txt_phase,tokenDetail.state);
    }

    private void updateShowState(TextView txt_phase, int state){
        if(state == 0){ //大使阶段
            txt_phase.setText(context.getString(R.string.home_phase_advisor));
            txt_phase.setTextColor(context.getResources().getColor(R.color.green_00DF86));
            txt_phase.setBackgroundResource(R.drawable.circle_phase_green_bg);
        }else if(state == 1){ //新，没开启swap阶段
            txt_phase.setText(context.getString(R.string.home_phase_new));
            txt_phase.setTextColor(context.getResources().getColor(R.color.yellow_FDD765));
            txt_phase.setBackgroundResource(R.drawable.circle_phase_yellow_bg);
        }else if(state == 3){ //将要下线，关闭swap阶段
            txt_phase.setText(context.getString(R.string.home_phase_down));
            txt_phase.setTextColor(context.getResources().getColor(R.color.red_DC4D4D));
            txt_phase.setBackgroundResource(R.drawable.circle_phase_red_bg);
        }else {

        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        //TODO 局部刷新
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            int type = getItemViewType(position);
            if (type == TOKEN_TYPE) {
                TokenDetail tokenDetail = list.get(position).token;
                TokenHolder tokenHolder = (TokenHolder) holder;
                updateItem(tokenDetail, tokenHolder);
            } else if (type == HEAD_TYPE) {
                HeaderHolder headerHolder = (HeaderHolder) holder;

            }
        }
    }

    @Override
    public int getItemViewType(int position) {
        HomeModel model = list.get(position);
        return model.type;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public boolean shouldHideDivider(int position, RecyclerView parent) {
        return position < 2;
    }

    static class HeaderHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.txt_head_total)
        TextView txt_head_total;

        @BindView(R.id.txt_head_value)
        TextView txt_head_value;

        @BindView(R.id.txt_my_balance)
        TextView txt_my_balance;

        @BindView(R.id.txt_4d_total)
        TextView txt_4d_total;

        @BindView(R.id.txt_home_pending)
        TextView txt_home_pending;

        @BindView(R.id.img_eye)
        ImageView img_eye;

        public HeaderHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

    static class TitleHolder extends RecyclerView.ViewHolder {
        public TitleHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    static class TokenHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.img_coin)
        ImageView img_coin;

        @BindView(R.id.txt_coin_name)
        TextView txt_coin_name;

        @BindView(R.id.txt_coin_change)
        TextView txt_coin_change;

        @BindView(R.id.txt_coin_price)
        TextView txt_coin_price;

        @BindView(R.id.txt_phase)
        TextView txt_phase;

        public TokenHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

    /**
     * 获取待确认订单数量
     *
     * @param pending
     * @return
     */
    String getPending(int pending) {
        return String.format(context.getResources().getString(R.string.home_dex4d_pending), pending);
    }

}
